import axios from 'axios'
import { Toast } from 'vant';
import router from '../router/router'
// axios.defaults.baseURL = 'https://www.fastmock.site/mock/d7f427c60566a4ab8a7cd79e33c87c7a/artical'
axios.defaults.baseURL = "/api"//服务器公网ip
// 请求超时
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// axios.defaults.headers['token'] = localStorage.getItem('token') || ''

// axios.defaults.withCredentials = true //跨域请求可以携带cookie

// 请求拦截
axios.interceptors.request.use((config)=>{
    let jwtToken = window.localStorage.getItem('token')
    // console.log('拦截器',jwtToken);
    if(jwtToken) {
        // config.headers.authorization = jwtToken
        config.headers.common['Authorization'] = 'Bearer ' + jwtToken;
    }

    return config
})



// 响应拦截
axios.interceptors.response.use(res => {
    // console.log('响应拦截器',res)
    if(typeof res.data !== 'object'){
        Toast.fail('服务器异常,请稍后再试')
        return Promise.reject(res)
    }
    if(res.data.code !== 200) {
        if(res.data.message) Toast.fail(res.data.message)
        if(res.data.code == 416){
            router.push('/qunar/login')
            // window.localStorage.setItem("isLogin", false);
        }
        if(res.data.code==301) {
           setTimeout(()=>{
            router.push(res.data.url)
           },1000)
        }
        return Promise.reject(res.data)
    }
    
    return res.data
})
export default axios

